package Records.Attributes;

import Records.Database.DuplicateEntry;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author Alexander
 */
public class SaveFeedData {

    private final ArrayList<FeedDataValues> feedData;
    static ArrayList song;
    private static int RssSongCounter;
    private static ArrayList<String> valSet;
    private static String CurSavedSong;

    /**
     * @return the feedData
     */
    public ArrayList<FeedDataValues> getFeedData() {
        System.out.println("SaveFeedData.getFeedData()");
        return feedData;
    }

    public SaveFeedData() {
        System.out.println("SaveFeedData.SaveFeedData()");
        feedData = new ArrayList<>();
    }

    public void Save(String Token, String Location, ArrayList RssString) {
        System.out.println("SaveFeedData.Save(" + Token + ", " + Location + ", " + RssString + ")");
        String originalTitle, originalMusicians, RssTitle = null, musicians = null;
        StringTokenizer st;
        int count = 0;
        String bpms, theKeys, Danceability, Energy, Acousticness, albumTitles, RssGenres;
        while (count < 2) {
            st = new StringTokenizer(RssString.get(count).toString(), Token);
            if (count == 0) {
                originalTitle = st.nextElement().toString();
                RssTitle = AttributeCleaner.cleanAttribute("Title", originalTitle);
            }
            if (count == 1) {
                originalMusicians = st.nextElement().toString();
                musicians = AttributeCleaner.cleanAttribute("Artist", originalMusicians);
            }
            count++;
        }
        setRssSongCounter(getRssSongCounter() + 1);
        if (RssTitle != null && musicians != null) {
            valSet = DuplicateEntry.getValues(RssTitle.replaceAll("/", "-"), musicians);
            if (valSet != null) {
                RssTitle = valSet.get(0);
                musicians = valSet.get(1);
                bpms = valSet.get(2);
                theKeys = valSet.get(3).replace(";", "");
                Danceability = valSet.get(4);
                Energy = valSet.get(5);
                Acousticness = valSet.get(6);
                albumTitles = valSet.get(7);
                RssGenres = valSet.get(8);
                String FilePathway = valSet.get(9);
                String PurchaseLink = valSet.get(10);
                String Song_ID = RssTitle + "_" + musicians + "_" + albumTitles;
                String images = "";

                setCurSavedSong("Importing: " + RssTitle + " - " + musicians + " - " + Location);
                System.out.println("");
                System.out.println("Importing " + RssTitle + " by: " + musicians);

                getFeedData().add(new FeedDataValues(Song_ID, RssTitle, bpms, RssGenres, Danceability, Energy, Acousticness, theKeys, Location, FilePathway, PurchaseLink, albumTitles, images, musicians));
            } else {
                String previousLocation;
                int feedDataSize = getFeedData().size();
                ArrayList<FeedDataValues> feedDataSet = getFeedData();

                for (int x = 0; x < feedDataSize; x++) {
                    FeedDataValues feedVal = feedDataSet.get(x);
                    if (RssTitle.equals(feedVal.getRssTitle())) {
                        if (musicians.equals(feedVal.getMusicians())) {
                            previousLocation = feedVal.getLocation();
                            feedVal.setLocation(previousLocation + " " + Location);
                            System.out.println(feedVal.getLocation());
                            break;
                        }
                    }
                }
            }
        }
    }

    public void ReadRunner(FeedDataKeys key) {
        System.out.println("SaveFeedData.ReadRunner(" + key + ")");

        String UrlPath = key.getUrlPath();
        String Location = key.getLocation();
        String Token = key.getToken();
        int numVar = key.getNumVar();
        String Order = key.getOrder();
        String xpathTitle = key.getXpathTitle();
        String xpathArtist = key.getXpathArtist();
        String InType = key.getInType();
        String[][] RssString = key.getRssString();
        int numOfSongs = key.getNumOfSongs();
        NodeList trackNameNodes;
        String path;

        for (int i = 0; i < numOfSongs; i++) {
            try {
                song = new ArrayList();
                if (InType.equals("XML")) {
                    for (int x = 0; x < numVar; x++) {
                        if (x == 0) {
                            path = xpathTitle;
                        } else {
                            path = xpathArtist;
                        }
                        URL url = new URL(UrlPath);
                        DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
                        XPathFactory XPATH_FACTORY = XPathFactory.newInstance();
                        URLConnection connection = url.openConnection();
                        DocumentBuilder db = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
                        Document document = null;
                        try {
                            document = db.parse(connection.getInputStream());
                        } catch (java.net.SocketException ex) {
                            ReadRunner(key);
                        }
                        XPath xPathEvaluator;
                        xPathEvaluator = XPATH_FACTORY.newXPath();
                        XPathExpression nameExpr;
                        nameExpr = xPathEvaluator.compile(path);
                        trackNameNodes = (NodeList) nameExpr.evaluate(document, XPathConstants.NODESET);

                        if (trackNameNodes != null) {
                            Node trackNameNode = trackNameNodes.item(i);
                            String b = trackNameNode.getTextContent().trim();
                            String theString = b.replace(" - ", "~").replace((i + 1) + ":", "").trim();
                            if (numVar == 1) {
                                if (Order.equals("Artist_Title")) {
                                    String theString2 = theString.substring(0, theString.indexOf("~")).replace("~", "");
                                    String theString1 = theString.replace(theString2, "");
                                    song.add(theString1);
                                    song.add(theString2);
                                } else {
                                    String theString1 = theString.substring(0, theString.indexOf("~")).replace("~", "");
                                    song.add(theString1);
                                    String theString2 = theString.replace(theString1, "");
                                    song.add(theString2);
                                }
                            } else {
                                song.add(theString);
                            }
                        }
                    }
                } else {
                    song = new ArrayList();
                    if (Order.equals("Artist_Title")) {
                        song.add(RssString[i][0]);
                        song.add(RssString[i][1]);
                    } else {//Title_Artist
                        song.add(RssString[i][1]);
                        song.add(RssString[i][0]);
                    }
                }
                Save(Token, Location, song);
            } catch (Exception Ex) {
                Ex.printStackTrace();
            }
        }

    }

    /**
     * @return the arrayCounter
     */
    public static int getRssSongCounter() {
        return RssSongCounter;
    }

    /**
     * @param aArrayCounter the arrayCounter to set
     */
    public static void setRssSongCounter(int aArrayCounter) {
        System.out.println("SaveFeedData.setArrayCounter(" + aArrayCounter + ")");
        RssSongCounter = aArrayCounter;
    }

    /**
     * @return the CurSavedSong
     */
    public static String getCurSavedSong() {
        return CurSavedSong;
    }

    /**
     * @param aCurSavedSong the CurSavedSong to set
     */
    public static void setCurSavedSong(String aCurSavedSong) {
        System.out.println("SaveFeedData.setCurSavedSong(" + aCurSavedSong + ")");
        CurSavedSong = aCurSavedSong;
    }
}
